package com.nanjia.boot.commonservice;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nanjia.boot.common.enums.OrderStatusEnum;
import com.nanjia.boot.common.enums.OrderTypeEnum;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.common.exception.BusinessException;
import com.nanjia.boot.common.result.Result;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.delivery.model.entity.DeliveryAddress;
import com.nanjia.boot.delivery.model.vo.DeliveryAddressVO;
import com.nanjia.boot.delivery.service.DeliveryAddressService;
import com.nanjia.boot.myflow.deliveryaddressflow.model.entity.DeliveryAddressFlow;
import com.nanjia.boot.myflow.deliveryaddressflow.model.form.DeliveryAddressFlowForm;
import com.nanjia.boot.myflow.deliveryaddressflow.model.query.DeliveryAddressFlowQuery;
import com.nanjia.boot.myflow.deliveryaddressflow.model.vo.DeliveryAddressFlowVO;
import com.nanjia.boot.myflow.deliveryaddressflow.service.DeliveryAddressFlowService;
import com.nanjia.boot.myflow.order.dto.OrderDTO;
import com.nanjia.boot.myflow.order.item.converter.OrderItemConverter;
import com.nanjia.boot.myflow.order.item.model.entity.OrderItem;
import com.nanjia.boot.myflow.order.item.model.form.OrderItemForm;
import com.nanjia.boot.myflow.order.item.model.query.OrderItemQuery;
import com.nanjia.boot.myflow.order.item.model.vo.OrderItemVO;
import com.nanjia.boot.myflow.order.item.service.OrderItemService;
import com.nanjia.boot.myflow.order.model.entity.Order;
import com.nanjia.boot.myflow.order.model.form.OodForm;
import com.nanjia.boot.myflow.order.model.form.OrderForm;
import com.nanjia.boot.myflow.order.model.form.ReturnOrderForm;
import com.nanjia.boot.myflow.order.model.query.OrderQuery;
import com.nanjia.boot.myflow.order.model.vo.OrderVO;
import com.nanjia.boot.myflow.order.service.OrderService;
import com.nanjia.boot.myflow.outboundorderdetail.model.form.OutboundOrderDetailForm;
import com.nanjia.boot.myflow.outboundorderdetail.service.OutboundOrderDetailService;
import com.nanjia.boot.product.sku.model.entity.ProductSku;
import com.nanjia.boot.product.sku.model.form.ProductSkuForm;
import com.nanjia.boot.product.sku.model.query.ProductSkuQuery;
import com.nanjia.boot.product.sku.model.vo.ProductSkuVO;
import com.nanjia.boot.product.sku.service.ProductSkuService;
import com.nanjia.boot.product.spu.model.entity.ProductSpu;
import com.nanjia.boot.product.spu.service.ProductSpuService;
import com.nanjia.boot.system.model.entity.SysDept;
import com.nanjia.boot.system.model.query.DeptQuery;
import com.nanjia.boot.system.service.SysDeptService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 这个才是面向controller的service，不要在controller中引入对应的service，避免循环依赖
 *
 * @author 周洋
 * @since Created in 2025 2025/7/30 11:09
 */
@Component
@RequiredArgsConstructor
public class CommonServiceImpl {

    private final OrderService orderService;

    private final OrderItemService orderItemService;

    private final ProductSkuService productSkuService;

    private final DeliveryAddressFlowService deliveryAddressFlowService;
    private final DeliveryAddressService deliveryAddressService;

    private final ProductSpuService productSpuService;

    private final OutboundOrderDetailService outboundOrderDetailService;

    private final SysDeptService deptService;
    private final OrderItemConverter orderItemConverter;

    /**
     * 订单商品明细分页列表
     *
     * @return {@link IPage < OrderItemVO >} 订单商品明细分页列表
     */
    public IPage<OrderItemVO> getOrderItemPage(OrderItemQuery queryParams) {
        return orderItemService.getOrderItemPage(queryParams);
    }

    /**
     * 获取订单商品明细表单数据
     *
     * @param id 订单商品明细ID
     * @return 订单商品明细表单数据
     */
    public OrderItemForm getOrderItemFormData(Long id) {
        return orderItemService.getOrderItemFormData(id);
    }

    /**
     * 新增订单商品明细
     *
     * @param formData 订单商品明细表单对象
     * @return 是否新增成功
     */
    public boolean saveOrderItem(OrderItemForm formData) {
        return orderItemService.saveOrderItem(formData);
    }

    /**
     * 修改订单商品明细
     *
     * @param id       订单商品明细ID
     * @param formData 订单商品明细表单对象
     * @return 是否修改成功
     */
    public boolean updateOrderItem(Long id, OrderItemForm formData) {
        return orderItemService.updateOrderItem(id, formData);
    }

    /**
     * 删除订单商品明细
     *
     * @param ids 订单商品明细ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    public boolean deleteOrderItems(String ids) {
        return orderItemService.deleteOrderItems(ids);
    }

    public boolean addItemToCart(@Valid OrderItemForm formData, String ipAddr) {

        OrderForm cartOrder = orderService.getCartOrderFormByUser(ipAddr);
        if (formData.getOrderId().longValue() != cartOrder.getId().longValue()) {
            return false;
        }
        return orderItemService.addItemToCart(formData, ipAddr, cartOrder);
    }

    public List<OrderItemVO> getOrderItemList(OrderItemQuery queryParams) {
        return orderItemService.getOrderItemList(queryParams);
    }

    public List<OrderItemVO> getOrderItemList(List<Long> orderIds) {
        return orderItemService.getOrderItemList(orderIds);
    }


    /**
     * 订单主分页列表
     *
     * @return {@link IPage< OrderVO >} 订单主分页列表
     */
    public IPage<OrderVO> getOrderPage(OrderQuery queryParams) {
        IPage<OrderVO> pageVO = orderService.getOrderPage(queryParams);
        List<OrderVO> records = pageVO.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return pageVO;
        }
        List<Long> orderIds = records.stream().map(OrderVO::getId).collect(Collectors.toList());
        List<OrderItemVO> orderItemListByids = orderItemService.list(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIds)).stream().map(orderItemConverter::toVo).toList();

        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, orderItemListByids.stream().map(OrderItemVO::getSkuId).collect(Collectors.toList())));

        List<ProductSpu> productSpuList = productSpuService.list(new LambdaQueryWrapper<ProductSpu>().in(ProductSpu::getId, productSkuList.stream().map(ProductSku::getSpuId).collect(Collectors.toList())));
        for (OrderItemVO orderItemVO : orderItemListByids) {
            for (ProductSku productSku : productSkuList) {
                if (productSku.getId().longValue() == orderItemVO.getSkuId().longValue()) {
                    if (StringUtils.isEmpty(productSku.getMainImage())) {
                        for (ProductSpu productSpu : productSpuList) {
                            if (productSpu.getId().longValue() == productSku.getSpuId().longValue()) {
                                orderItemVO.setMainImage(productSpu.getMainImage());
                                break;
                            }
                        }
                    } else {
                        orderItemVO.setMainImage(productSku.getMainImage());
                        break;
                    }

                }
            }
        }

        // 遍历每个 OrderVO，将对应的 OrderItemVO 填充到 orderItems 列表中
        for (OrderVO orderVO : records) {
            // 过滤出 orderItemListByids 中 orderId 匹配的 OrderItemVO
            List<OrderItemVO> matchedItems = orderItemListByids.stream()
                    .filter(item -> item.getOrderId().equals(orderVO.getId())) // 比对 orderId
                    .collect(Collectors.toList());

            // 将匹配到的 OrderItemVO 列表设置到 OrderVO 的 orderItems 字段
            orderVO.setOrderItems(matchedItems);
        }
        List<DeliveryAddressFlowVO> deliveryAddressFlows = getDAFlowList(orderIds);
        // 遍历每个 OrderVO，将对应的 OrderItemVO 填充到 orderItems 列表中
        for (OrderVO orderVO : records) {
            // 过滤出 orderItemListByids 中 orderId 匹配的 OrderItemVO
            List<DeliveryAddressFlowVO> matchedItems = deliveryAddressFlows.stream()
                    .filter(deliveryAddressFlowVO -> deliveryAddressFlowVO.getOrderId().longValue() == orderVO.getId().longValue()) // 比对 orderId
                    .collect(Collectors.toList());

            // 将匹配到的 OrderItemVO 列表设置到 OrderVO 的 orderItems 字段
            orderVO.setDeliveryAddressFlows(matchedItems);
        }
        return pageVO;
    }

    /**
     * 获取订单主表单数据
     *
     * @param id 订单主ID
     * @return 订单主表单数据
     */
    public OrderForm getOrderFormData(Long id) {
        return orderService.getOrderFormData(id);
    }

    /**
     * 新增订单主
     *
     * @param formData 订单主表单对象
     * @return 是否新增成功
     */
    public boolean saveOrder(OrderForm formData) {
        return orderService.saveOrder(formData);
    }

    /**
     * 修改订单主
     *
     * @param id       订单主ID
     * @param formData 订单主表单对象
     * @return 是否修改成功
     */
    public boolean updateOrder(Long id, OrderForm formData) {
        return orderService.updateOrder(id, formData);
    }

    /**
     * 删除订单主
     *
     * @param ids 订单主ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    public boolean deleteOrders(String ids) {
        return orderService.deleteOrders(ids);
    }

    public OrderForm getCartOrderFormByUser(String ipAddr) {
        return orderService.getCartOrderFormByUser(ipAddr);
    }

    @Transactional(rollbackFor = BusinessException.class)
    public Result<Void> createOrder(OrderForm formData, String ipAddr) {
        List<DeliveryAddressVO> deliveryAddresses = formData.getDeliveryAddresses();
        if (CollectionUtils.isEmpty(deliveryAddresses) || deliveryAddresses.size() != 2) {
            throw new BusinessException("缺少收货/收票地址");
        }

        DeliveryAddressFlow deliveryAddressFlow0 = new DeliveryAddressFlow();
        DeliveryAddressFlow deliveryAddressFlow1 = new DeliveryAddressFlow();

        for (DeliveryAddressVO deliveryAddressVO : formData.getDeliveryAddresses()) {
            DeliveryAddress deliveryAddress = deliveryAddressService.selectById(deliveryAddressVO.getId());
            if (deliveryAddress != null) {
                if (deliveryAddress.getDeliveryType().intValue() == 0) {
                    deliveryAddressFlow0.setDeliveryType(0);
                    deliveryAddressFlow0.setDeliveryName(deliveryAddress.getDeliveryName());
                    deliveryAddressFlow0.setDeliveryPhone(deliveryAddress.getDeliveryPhone());
                    deliveryAddressFlow0.setPostalCode(deliveryAddress.getPostalCode());
                    deliveryAddressFlow0.setDeliveryProvince(deliveryAddress.getDeliveryProvince());
                    deliveryAddressFlow0.setDeliveryCity(deliveryAddress.getDeliveryCity());
                    deliveryAddressFlow0.setDeliveryDetail(deliveryAddress.getDeliveryDetail());
                    deliveryAddressFlow0.setDeliveryArea(deliveryAddress.getDeliveryArea());
                    deliveryAddressFlow0.setDeliveryAddressId(deliveryAddress.getId());
                    deliveryAddressFlow0.setDeliveryDefault(deliveryAddress.getDeliveryDefault());
                    deliveryAddressFlow0.setCreateTime(LocalDateTime.now());
                    deliveryAddressFlow0.setUpdateTime(LocalDateTime.now());
                    deliveryAddressFlow0.setUpdateIp(ipAddr);
                    deliveryAddressFlow0.setCreateIp(ipAddr);
                    deliveryAddressFlow0.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                    deliveryAddressFlow0.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
                    deliveryAddressFlow0.setDeliveryCode(deliveryAddress.getDeliveryCode());
                    deliveryAddressFlow0.setSubdomainCode(deliveryAddress.getSubdomainCode());
                    deliveryAddressFlow0.setSubdomainUserCode(deliveryAddress.getSubdomainUserCode());
                    boolean save = deliveryAddressFlowService.save(deliveryAddressFlow0);
                    if (!save) {
                        throw new BusinessException("地址不存在");
                    }
                } else if (deliveryAddress.getDeliveryType().intValue() == 1) {
                    deliveryAddressFlow1.setDeliveryType(deliveryAddress.getDeliveryType());
                    deliveryAddressFlow1.setDeliveryName(deliveryAddress.getDeliveryName());
                    deliveryAddressFlow1.setDeliveryPhone(deliveryAddress.getDeliveryPhone());
                    deliveryAddressFlow1.setPostalCode(deliveryAddress.getPostalCode());
                    deliveryAddressFlow1.setDeliveryProvince(deliveryAddress.getDeliveryProvince());
                    deliveryAddressFlow1.setDeliveryCity(deliveryAddress.getDeliveryCity());
                    deliveryAddressFlow1.setDeliveryDetail(deliveryAddress.getDeliveryDetail());
                    deliveryAddressFlow1.setDeliveryArea(deliveryAddress.getDeliveryArea());
                    deliveryAddressFlow1.setDeliveryAddressId(deliveryAddress.getId());
                    deliveryAddressFlow1.setDeliveryDefault(deliveryAddress.getDeliveryDefault());
                    deliveryAddressFlow1.setCreateTime(LocalDateTime.now());
                    deliveryAddressFlow1.setUpdateTime(LocalDateTime.now());
                    deliveryAddressFlow1.setUpdateIp(ipAddr);
                    deliveryAddressFlow1.setCreateIp(ipAddr);
                    deliveryAddressFlow1.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                    deliveryAddressFlow1.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
                    deliveryAddressFlow1.setDeliveryCode(deliveryAddress.getDeliveryCode());
                    deliveryAddressFlow1.setSubdomainCode(deliveryAddress.getSubdomainCode());
                    deliveryAddressFlow1.setSubdomainUserCode(deliveryAddress.getSubdomainUserCode());
                    boolean save = deliveryAddressFlowService.save(deliveryAddressFlow1);
                    if (!save) {
                        throw new BusinessException("地址不存在");
                    }
                }
            } else {
                throw new BusinessException("地址不存在");
            }
        }

        List<DeliveryAddressFlow> deliveryAddressFlows = new ArrayList<>();
        deliveryAddressFlows.add(deliveryAddressFlow0);
        deliveryAddressFlows.add(deliveryAddressFlow1);

        //检测是否是直接下单
        if (formData.getSkuId() != null) {
            ProductSkuForm productSkuFormData = productSkuService.getProductSkuFormData(formData.getSkuId());
            ProductSpu productSpu = productSpuService.getById(productSkuFormData.getSpuId());
            if (productSkuFormData.getStatus().intValue() != StatusEnum.ENABLE.getValue()) {
                throw new BusinessException("存在不可售商品");
            }


            Order order = orderService.createOrder(formData, ipAddr, deliveryAddressFlows);
            if (order != null) {

                List<OrderItem> insertOrderItemList = new ArrayList<>();

                OrderItem item = new OrderItem();
                item.setItemCode("MALL" + SecurityUtils.getUserId() + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
                item.setOrderId(order.getId());
                item.setSkuId(formData.getSkuId());
                item.setProductName(productSpu.getSpuName());
                item.setQuantity(formData.getCount());
                item.setUpdateIp(ipAddr);
                item.setUpdateTime(LocalDateTime.now());
                item.setCreateTime(LocalDateTime.now());
                item.setCreateIp(ipAddr);
                item.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                item.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
                item.setSkuSpecs(productSkuFormData.getSpecValueIds());
                item.setPrice(productSkuFormData.getPrice());
                item.setDaf0Id(deliveryAddressFlow0.getId());
                item.setDaf1Id(deliveryAddressFlow1.getId());
                insertOrderItemList.add(item);
                Integer insertBatch = orderItemService.insertBatch(insertOrderItemList);
                if (insertBatch > 0) {
                    return Result.success();
                }
            }
            return Result.failed("创建订单失败");
        }
        if (CollectionUtils.isEmpty(formData.getOrderItems())) {
            return Result.failed("请先选择商品");
        }
        for (OrderItemVO itemVO : formData.getOrderItems()) {
            Long skuId = itemVO.getSkuId();
            ProductSkuForm productSkuFormData = productSkuService.getProductSkuFormData(skuId);
            if (productSkuFormData == null) {
                return Result.failed("商品不存在");
            }
            if (productSkuFormData.getStatus().intValue() != StatusEnum.ENABLE.getValue()) {
                return Result.failed("存在不可售商品");
            }
        }
        Order order = orderService.createOrder(formData, ipAddr, deliveryAddressFlows);
        if (order != null) {
            //这一段可以抽象到orderItemService
            List<OrderItem> insertOrderItemList = new ArrayList<>();

            for (OrderItemVO orderItemVO : formData.getOrderItems()) {
                OrderItem item = new OrderItem();
                item.setItemCode("MALL" + SecurityUtils.getUserId() + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
                item.setOrderId(order.getId());
                item.setSkuId(orderItemVO.getSkuId());
                item.setProductName(orderItemVO.getProductName());
                item.setQuantity(orderItemVO.getQuantity());
                item.setUpdateIp(ipAddr);
                item.setUpdateTime(LocalDateTime.now());
                item.setCreateTime(LocalDateTime.now());
                item.setCreateIp(ipAddr);
                item.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                item.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
                item.setSkuSpecs(orderItemVO.getSkuSpecs());
                item.setPrice(orderItemVO.getPrice());
                item.setDaf0Id(deliveryAddressFlow0.getId());
                item.setDaf1Id(deliveryAddressFlow1.getId());
                insertOrderItemList.add(item);

            }
            Integer insertBatch = orderItemService.insertBatch(insertOrderItemList);

            List<OrderItem> orderItemList = new ArrayList<>();
            orderItemService.deleteOrderItems(formData.getOrderItems().stream().map(orderItem -> String.valueOf(orderItem.getId())).collect(Collectors.joining(",")));
            return Result.success();

        }
        return Result.failed("创建订单失败");
    }

    /**
     * 商品库存单元(SKU)分页列表
     *
     * @return {@link IPage< ProductSkuVO >} 商品库存单元(SKU)分页列表
     */
    IPage<ProductSkuVO> getProductSkuPage(ProductSkuQuery queryParams) {
        return productSkuService.getProductSkuPage(queryParams);
    }

    /**
     * 获取商品库存单元(SKU)表单数据
     *
     * @param id 商品库存单元(SKU)ID
     * @return 商品库存单元(SKU)表单数据
     */
    ProductSkuForm getProductSkuFormData(Long id) {
        return productSkuService.getProductSkuFormData(id);
    }


    /**
     * 收货/收票信息流水分页列表
     *
     * @return {@link IPage< DeliveryAddressFlowVO >} 收货/收票信息流水分页列表
     */
    IPage<DeliveryAddressFlowVO> getDeliveryAddressFlowPage(DeliveryAddressFlowQuery queryParams) {
        return deliveryAddressFlowService.getDeliveryAddressFlowPage(queryParams);
    }

    /**
     * 获取收货/收票信息流水表单数据
     *
     * @param id 收货/收票信息流水ID
     * @return 收货/收票信息流水表单数据
     */
    DeliveryAddressFlowForm getDeliveryAddressFlowFormData(Long id) {
        return deliveryAddressFlowService.getDeliveryAddressFlowFormData(id);
    }

    /**
     * 新增收货/收票信息流水
     *
     * @param formData 收货/收票信息流水表单对象
     * @return 是否新增成功
     */
    boolean saveDeliveryAddressFlow(DeliveryAddressFlowForm formData) {
        return deliveryAddressFlowService.saveDeliveryAddressFlow(formData);
    }

    /**
     * 修改收货/收票信息流水
     *
     * @param id       收货/收票信息流水ID
     * @param formData 收货/收票信息流水表单对象
     * @return 是否修改成功
     */
    boolean updateDeliveryAddressFlow(Long id, DeliveryAddressFlowForm formData) {
        return deliveryAddressFlowService.updateDeliveryAddressFlow(id, formData);
    }

    /**
     * 删除收货/收票信息流水
     *
     * @param ids 收货/收票信息流水ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    boolean deleteDeliveryAddressFlows(String ids) {
        return deliveryAddressFlowService.deleteDeliveryAddressFlows(ids);
    }

    List<DeliveryAddressFlowVO> getDAFlowList(List<Long> orderIds) {
        return deliveryAddressFlowService.getDAFlowList(orderIds);
    }

    public boolean createOrderByOld(OrderForm formData, String ipAddr) {
        List<OrderItem> orderItems = orderItemService.selectOrderItemsByOrderId(formData.getId());

        OrderForm cartOrderFormByUser = orderService.getCartOrderFormByUser(ipAddr);
        List<OrderItem> cartOrderItems = orderItemService.selectOrderItemsByOrderId(cartOrderFormByUser.getId());
        for (OrderItem item : orderItems) {
            OrderItemForm orderItemForm = new OrderItemForm();
            orderItemForm.setOrderId(cartOrderFormByUser.getId());
            orderItemForm.setSkuId(item.getSkuId());
            orderItemForm.setQuantity(item.getQuantity());
            orderItemForm.setProductName(item.getProductName());
            orderItemService.addItemToCart(orderItemForm, ipAddr, cartOrderFormByUser);
        }
        return true;
//// 构建购物车项的skuId映射
//        Map<Long, OrderItem> cartItemMap = new HashMap<>();
//        for (OrderItem cartItem : cartOrderItems) {
//            cartItemMap.put(cartItem.getSkuId(), cartItem);
//        }
//        List<OrderItem> insertOrderItems = new ArrayList<>();
//        try {
//            for (OrderItem item : orderItems) {
//                Long skuId = item.getSkuId();
//                if (cartItemMap.containsKey(skuId)) {
//                    // 更新现有购物车项的数量
//                    OrderItem cartItem = cartItemMap.get(skuId);
//                    cartItem.setQuantity(item.getQuantity());
//                    cartItem.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId())); // 更新操作人
//                    cartItem.setUpdateIp(ipAddr);   // 更新IP
//                    orderItemService.updateById(cartItem);
//                } else {
//                    // 创建新购物车项
////                    insertOrderItems.add(newItem); // 保持内存数据同步
//                    OrderItemForm orderItemForm = new OrderItemForm();
//                    orderItemForm.setOrderId(cartOrderFormByUser.getId());
//                    orderItemForm.setSkuId(skuId);
//                    orderItemForm.setQuantity(item.getQuantity());
//                    orderItemForm.setProductName(item.getProductName());
//                    orderItemService.addItemToCart(orderItemForm,ipAddr,cartOrderFormByUser);
//                }
//
//            }
//
//            return true;
//        } catch (Exception e) {
//            return false;
//        }
    }

    public Result updateOrderStatus(OrderForm formData, String ipAddr) {

        if (formData.getStatus() == null) {
            return Result.failed("状态为空");
        }
        if (formData.getStatus().intValue() == OrderStatusEnum.Status5.getValue()) {
            formData.setTotalAmount(null);
//            orderService.updateOrder(formData.getId(), formData);
//            List<OrderItem> orderItems = orderItemService.selectOrderItemsByOrderId(formData.getId());
//            for (OrderItem item : orderItems) {
//                if (item != null) {
//                    List<SkuStock> skuStocks = skuStockService.list(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, item.getSkuId()).orderByDesc(SkuStock::getId));
//                    if (CollectionUtils.isNotEmpty(skuStocks)) {
//                        SkuStock updateSkuStock = new SkuStock();
//                        updateSkuStock.setId(skuStocks.get(0).getId());
//                        int i = skuStocks.get(0).getLockedStock() - item.getQuantity();
//                        updateSkuStock.setLockedStock(i > -1 ? i : 0);
//                        skuStockService.updateById(updateSkuStock);
//                    }
//                }
//
//            }
//            orderItemService.deleteOrderItems(orderItems.stream().map(orderItem -> String.valueOf(orderItem.getId())).collect(Collectors.joining(",")));
            return Result.judge(orderService.updateOrder(formData.getId(), formData));
        }
        return Result.failed("暂不支持此业务");
    }

    public Result updateEmsStatus(OodForm formData, String ipAddr) {
        OutboundOrderDetailForm outboundOrderDetailForm = new OutboundOrderDetailForm();
        outboundOrderDetailForm.setId(formData.getOodid());
        outboundOrderDetailForm.setStatus(formData.getEmsstatus());
        boolean b = outboundOrderDetailService.updateOutboundOrderDetail(formData.getOodid(), outboundOrderDetailForm);
        return Result.judge(b);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Object> returnOrder(List<ReturnOrderForm> returnOrderForms, String ipAddr) {

        List<Long> orderItemIds = returnOrderForms.stream().map(ReturnOrderForm::getOrderItemId).toList();
        List<OrderItem> orderItemList = orderItemService.list(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getId, orderItemIds).gt(OrderItem::getCompletedQuantity, 0));
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new BusinessException("退货发起失败");
        }
        for (OrderItem item : orderItemList) {
            if (item.getReturnQuantity().longValue() >= item.getCompletedQuantity().longValue()) {
                throw new BusinessException(item.getProductName() + "超退");
            }
        }


        //开始创建退货单
        Order returnOrder = createReturnOrder(returnOrderForms, orderItemList, ipAddr);
        return Result.success(returnOrder);
    }

    /**
     * @param returnOrderForms 来自于客户端，提供oodid和退货数量
     * @param orderItemList    来自于数据库的销售单明细列表
     * @param ipAddr           请求IP
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Order createReturnOrder(List<ReturnOrderForm> returnOrderForms, List<OrderItem> orderItemList, String ipAddr) {
        List<Long> itemIds = orderItemList.stream().map(OrderItem::getId).collect(Collectors.toList());
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<OrderItem> returnOrderItemList = new ArrayList<>();
        for (OrderItem item : orderItemList) {

            for (OrderItem orderItem : orderItemList) {

                for (ReturnOrderForm returnOrderForm : returnOrderForms) {
                    if (returnOrderForm.getOrderItemId().longValue() == orderItem.getId().longValue()) {
                        OrderItem returnOrderItem = new OrderItem();
                        returnOrderItem.setCreateIp(ipAddr);
                        returnOrderItem.setUpdateIp(ipAddr);
                        returnOrderItem.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                        returnOrderItem.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
                        returnOrderItem.setCreateTime(LocalDateTime.now());
                        returnOrderItem.setUpdateTime(LocalDateTime.now());
                        returnOrderItem.setSkuId(item.getSkuId());
                        returnOrderItem.setProductName(item.getProductName());
                        returnOrderItem.setSkuSpecs(item.getSkuSpecs());
                        returnOrderItem.setPrice(item.getPrice());
                        returnOrderItem.setQuantity(returnOrderForm.getReturnQuantity());

                        item.setReturnQuantity(item.getReturnQuantity() + returnOrderItem.getQuantity());
                        returnOrderItem.setDaf1Id(item.getDaf1Id());
                        returnOrderItem.setDaf0Id(item.getDaf0Id());
                        returnOrderItem.setRemark(returnOrderForm.getReturnReason());
                        returnOrderItem.setItemCode("RE" + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
                        returnOrderItem.setParentId(orderItem.getId());
                        returnOrderItemList.add(returnOrderItem);
                        totalAmount = totalAmount.add(returnOrderItem.getPrice().multiply(new BigDecimal(returnOrderForm.getReturnQuantity())));
                    }
                }

            }
        }
        Order order = new Order();
        order.setUserId(SecurityUtils.getUserId());
        order.setOrderSn("THDD" + SecurityUtils.getUserId() + new Date().getTime());
        order.setStatus(OrderStatusEnum.Status6.getValue());
        order.setCreateIp(ipAddr);
        order.setUpdateIp(ipAddr);
        order.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        order.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setTotalAmount(totalAmount);
        order.setRemark("退货单");
        order.setOrderType(OrderTypeEnum.RETURN.getValue());
        order.setParentId(orderItemList.get(0).getOrderId());
        boolean save = orderService.save(order);
        if (save) {
            for (OrderItem item : returnOrderItemList) {
                item.setOrderId(order.getId());
            }
            orderItemService.saveBatch(returnOrderItemList);
            Order oldOrder = new Order();
            oldOrder.setId(orderItemList.get(0).getOrderId());
            oldOrder.setStatus(OrderStatusEnum.Status11.getValue());
            orderService.updateById(oldOrder);
            orderItemService.updateBatchById(orderItemList);
            return order;
        }

        throw new BusinessException("创建退货单失败");
    }

    public List<OrderDTO> orderDTOList(OrderQuery queryParams) {
        DeptQuery deptQuery = new DeptQuery();
        List<SysDept> list = deptService.list(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, 0).eq(SysDept::getIsDeleted, 0));
        SysDept dept = list.get(0);
        List<OrderDTO> orderDTOList = orderService.orderDTOList(queryParams);
        for (OrderDTO orderDTO : orderDTOList) {
            orderDTO.commonMethod();
            orderDTO.setColAH(dept.getName());
            orderDTO.setColAI(dept.getName());
        }
        return orderDTOList;
    }
}
